﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace Micro.Core.ServiceDiscovery
{
    public class ConsulServiceDiscovery : IServiceDiscovery
    {
        private static string SERVICE_HOST = "http://localhost";
        private static string SERVICE_PORT = "8500";
        private static string SERVICE_LIST_URL = "/v1/catalog/service";
        public List<T> GetService<T>(string serviceName)
        {
            var baseUri = new Uri(SERVICE_HOST + ":" + SERVICE_PORT, UriKind.Absolute);
            var queryUrl = new Uri(baseUri, SERVICE_LIST_URL + "/" + serviceName);
            var result = Send(queryUrl);
            return JsonConvert.DeserializeObject<List<T>>(result);
        }

        public List<T> GetServices<T>()
        {
            throw new NotImplementedException();
        }

        private string Send(Uri url)
        {
            Stream instream = null;
            StreamReader sr;
            Stream outstream = null;
            HttpWebResponse response = null;
            HttpWebRequest webRequest = null;
            Encoding encoding = Encoding.UTF8;
            try
            {
                System.GC.Collect();
                // 准备请求...
                webRequest = (HttpWebRequest)WebRequest.Create(url);
                //webRequest.ServicePoint.ConnectionLimit = int.MaxValue;
                WebProxy webProxy = new WebProxy();
                webProxy.Address = new Uri("http://www.baidu.com");
                webRequest.Proxy = webProxy;
                webRequest.KeepAlive = false;
                webRequest.ServicePoint.Expect100Continue = false;
                //webRequest.Proxy = null;
                webRequest.Method = "GET";

                //发送请求并获取相应回应数据
                response = webRequest.GetResponse() as HttpWebResponse;

                //直到request.GetResponse()程序才开始向目标网页发送Post请求
                instream = response.GetResponseStream();
                sr = new StreamReader(instream, encoding);
                string content = sr.ReadToEnd();
                response.Close();
                response = null;
                return content;
            }
            catch (Exception e)
            {
                if (instream != null) instream.Close();
                if (outstream != null) outstream.Close();
                if (response != null) response.Close();
                if (webRequest != null) webRequest.Abort();
                throw e;
            }
        }
    }
}
